class_name UnitSpawner
extends Node

# ===============================================

signal unit_spawned(unit: Unit)

# ===============================================

@export var bench: PLayArea
@export var game_area: PLayArea
@export var game_state: GameState

# ===============================================

@onready var unit_scene_spawner: SceneSpawner = $UnitSceneSpawner

# ===============================================

func spawn_unit(unit: UnitStats) -> void:
	var area: PLayArea = __get_first_available_area()
	# TODO throw a popup error message
	assert(area, "No available space to add unit to!")
	
	var new_unit: Unit = unit_scene_spawner.spawn_scene(area.unit_grid) as Unit
	var tile: Vector2i = area.unit_grid.get_first_empty_tile()
	area.unit_grid.add_unit(tile, new_unit)
	new_unit.global_position = area.get_global_from_tile(tile) - Arena.HALF_CELL_SIZE
	new_unit.stats = unit
	unit_spawned.emit(new_unit)

# ===============================================

func __get_first_available_area() -> PLayArea:
	if not bench.unit_grid.is_grid_full():
		return bench
	elif not game_area.unit_grid.is_grid_full() and not game_state.is_battling():
		return game_area
	return null
